<?php

namespace App\Services\DingDing;

use App\Models\CompanyinfoDinding;
use App\Models\CompanyUserDinding;
use Illuminate\Support\Facades\DB;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
class DingDingSer
{





    public static function getAccessToken()
    {
        $key = 'dingding_access_token';
        $access_token = Redis::get($key);
        if($access_token){
            return $access_token;
        }else{
            $url='https://oapi.dingtalk.com/gettoken';

            $client= new Client();
            $response = $client->request('GET', $url.'?appkey='.env('DINGDING_APPKEY').'&appsecret='.env('DINGDING_APPSECRET'),
            ['headers' => ['Content-Type' => 'application/json;charset=utf-8']]);
            
            $res=json_decode($response->getBody()->getContents(),true);
            Log::info('获取token'.json_encode($res));
            if(isset($res['errcode']) && $res['errcode']==0 && isset($res['access_token']) && $res['access_token']){
                $access_token=$res['access_token'];
                Redis::setex($key,7000,$access_token);
                return $access_token;
            }else{
                return '';
            }
        }
    }



    public static function getDepartmentList(){
        $url='https://oapi.dingtalk.com/topapi/v2/department/listsub';
        $access_token=self::getAccessToken();
        if($access_token==''){
            throw new \Exception('access_token不存在');
        }
        $client= new Client();
        $response = $client->request('POST', $url.'?access_token='.$access_token,
        ['headers' => ['Content-Type' => 'application/json;charset=utf-8']]);
        $res=json_decode($response->getBody()->getContents(),true);
        // Log::info('钉钉获取部门列表'.json_encode($res));
        if(isset($res['errcode']) && $res['errcode']==0 ){
            $dept_id_list=$res['result'];

            $db_dept_id_list=[];
            foreach($dept_id_list as $dept_id){
                
                $url='https://oapi.dingtalk.com/topapi/v2/department/listsubid';

                $dept_id_response = $client->request('POST', $url.'?access_token='.$access_token,
                ['headers' => ['Content-Type' => 'application/json;charset=utf-8'],'body' => json_encode(['dept_id'=>$dept_id['dept_id']],JSON_UNESCAPED_UNICODE)]);
                $dept_idres=json_decode($dept_id_response->getBody()->getContents(),true);

                // Log::info('钉钉获取部门列表'.json_encode($dept_idres));
                if(isset($dept_idres['errcode']) && $dept_idres['errcode']==0 ){
                    $db_dept_id_list=array_merge($db_dept_id_list,$dept_idres['result']['dept_id_list']);
                }
            }


            // Log::info($db_dept_id_list);
            foreach($db_dept_id_list as $db_dept_id){

                $url='https://oapi.dingtalk.com/topapi/v2/department/get';

                $dept_info_response = $client->request('POST', $url.'?access_token='.$access_token,
                ['headers' => ['Content-Type' => 'application/json;charset=utf-8'],'body' => json_encode(['dept_id'=>$db_dept_id],JSON_UNESCAPED_UNICODE)]);
                $dept_infores=json_decode($dept_info_response->getBody()->getContents(),true);
                if(isset($dept_infores['errcode']) && $dept_infores['errcode']==0){
                    CompanyinfoDinding::updateOrCreate(
                        ['dept_id'=>$dept_infores['result']['dept_id']],
                        ['dept_id'=>$dept_infores['result']['dept_id'],'dinding_name'=>$dept_infores['result']['name'],'update_at'=>time()]
    
                    );
                }

                
            }
        }else{
            throw new \Exception('获取信息失败');
        }

    }


    public static function getDepartmentUserInfoList(){

        $cpd_list=CompanyinfoDinding::get()->toArray();
        $access_token=self::getAccessToken();
        if($access_token==''){
            throw new \Exception('access_token不存在');
        }
        foreach($cpd_list as $cpd){
            $url='https://oapi.dingtalk.com/topapi/v2/user/list';

            $data=[
               'dept_id'=>$cpd['dept_id'],
               'cursor'=>0,
               'size'=>100
           ];
            $client= new Client();
            
            $response = $client->request('POST', $url.'?access_token='.$access_token,
            ['headers' => ['Content-Type' => 'application/json;charset=utf-8'],
             'body' => json_encode($data,JSON_UNESCAPED_UNICODE)]);

            $res=json_decode($response->getBody()->getContents(),true);
            

            Log::info('钉钉获取部门列表'.json_encode($res));

            if(isset($res['errcode']) && $res['errcode']==0){
                $list=$res['result']['list'];
                foreach($list as $val){
                    CompanyUserDinding::updateOrCreate(
                        ['userid'=>$val['userid'],'cpd_id'=>$cpd['id']],
                        ['userid'=>$val['userid'],'cpd_id'=>$cpd['id'],'real_name'=>$val['name'],'update_at'=>time()]
    
                    );
                }
            }

        }



    }

    public static function  getDepartmentUserInfoListByDeptId(array $cpd){
        $access_token=self::getAccessToken();
        if($access_token==''){
            throw new \Exception('access_token不存在');
        }


        $url='https://oapi.dingtalk.com/topapi/v2/user/list';

            $data=[
               'dept_id'=>$cpd['dept_id'],
               'cursor'=>0,
               'size'=>100
           ];
            $client= new Client();
            
            $response = $client->request('POST', $url.'?access_token='.$access_token,
            ['headers' => ['Content-Type' => 'application/json;charset=utf-8'],
             'body' => json_encode($data,JSON_UNESCAPED_UNICODE)]);

            $res=json_decode($response->getBody()->getContents(),true);
            

            Log::info('钉钉获取部门列表'.json_encode($res));

            if(isset($res['errcode']) && $res['errcode']==0){
                $list=$res['result']['list'];
                foreach($list as $val){
                    CompanyUserDinding::updateOrCreate(
                        ['userid'=>$val['userid'],'cpd_id'=>$cpd['id']],
                        ['userid'=>$val['userid'],'cpd_id'=>$cpd['id'],'real_name'=>$val['name'],'update_at'=>time()]
    
                    );
                }
            }
    }




}